import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import axios from "axios";

export const fetchHomeMultiDataAction = createAsyncThunk(
    "fetch/homeMultiData",
    async () => {
    const res = await axios.get("http://123.207.32.32:8000/home/multidata")
    return res.data
})

const homeSlice = createSlice({
    name: "home",
    initialState: {
        banners: [],
        recommends: []
    },
    reducers: {
        changeBanners(state, {payload}) {
            state.banners = payload
        },
        changeRecommends(state, {payload}) {
            state.recommends = payload
        },
    },

    // extraReducers: {
    //     [fetchHomeMultiDataAction.pending](state, action) {
    //         console.log("fetchHomeMultiDataAction pending")
    //     },
    //     [fetchHomeMultiDataAction.fulfilled](state, {payload}) {
    //         console.log("fetchHomeMultiDataAction fulfilled")
    //         state.banners = payload.data.banner.list
    //         state.recommends = payload.data.recommend.list
    //     },
    //     [fetchHomeMultiDataAction.rejected](state, action) {
    //         console.log("fetchHomeMultiDataAction rejected")
    //     }
    // }


    //方式二:
    extraReducers: (builder) => {
        builder.addCase(fetchHomeMultiDataAction.pending, (state, action) => {
            console.log("fetchHomeMultiDataAction pending", state, state)
        }).addCase(fetchHomeMultiDataAction.fulfilled, (state, {payload}) => {
            console.log("fetchHomeMultiDataAction fulfilled")
            state.banners = payload.data.banner.list
            state.recommends = payload.data.recommend.list
        }).addCase(fetchHomeMultiDataAction.rejected, (state, action) => {
            console.log("fetchHomeMultiDataAction rejected", state, action)
        });
    }
})

export const {changeBanners, changeRecommends} = homeSlice.actions;
export default homeSlice.reducer;
